﻿using Furion.Logging;
using Furion.Logging.Extensions;

namespace Admin.NET.Application.Service;

/// <summary>
/// 公用Model,前端给表单设置一个固定的Code, 然后把完整的Model保存起来
/// </summary>
public class BasViewModelService : BaseService<BasViewModel>
{

    public BasViewModelService(IServiceScopeFactory scopeFactory) : base(scopeFactory)
    {
    }

    /// <summary>
    /// 查询列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task<SqlSugarPagedList<BasViewModel>> Page(BasViewModelPageInput input)
    {
        return await Queryable
           .WhereIF(input.Category.HasValue(), it => it.Category == input.Category)
           .WhereIF(input.Keyword.HasValue(), it => SqlFunc.JsonLike(it.Model, input.Keyword))
           .ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task<List<BasViewModel>> All(BasViewModelQueryInput input)
    {
        return await Queryable
           .WhereIF(input.Code.HasValue(), it => it.Code == input.Code)
           .WhereIF(input.Category.HasValue(), it => it.Category == input.Category)
           .ToListAsync();
    }

    /// <summary>
    /// 查询第一项
    /// </summary>
    public async Task<BasViewModel> QueryFirst(BasViewModelQueryInput input)
    {
        return await Queryable
          .Where(it => it.Code == input.Code)
          .WhereIF(input.Category.HasValue(), it => it.Category == input.Category)
          .FirstAsync();
    }

    /// <summary>
    /// 通过Id获取
    /// </summary>
    public async Task<BasViewModel> Get(long id)
    {
        var obj = await _rep.InSingleAsync(id);
        return obj;
    }

    /// <summary>
    /// 新增成功后返回主键
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task<long> Add(BasViewModelAddInput input)
    {
        var entity = new BasViewModel() { Code = input.Code, Category = input.Category, Model = input.Model };
        var obj = await _rep.InsertReturnEntityAsync(entity);
        return obj.Id;
    }

    /// <summary>
    /// 更新成功后返回true
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task<bool> Update(BasViewModelUpdateInput input)
    {
        var entity = new BasViewModel() { Id = input.Id, Code = input.Code, Category = input.Category, Model = input.Model };
        if (await _rep.UpdateAsync(entity))
        {
            return true;
        }
        else
        {
            ("更新失败:" + input.Id).LogError<BasViewModelService>();
            throw Oops.Oh("更新失败");
        }
    }
}